//
//  YZMPhoneNewViewController.m
//  YZMicroStock
//
//  Created by apple on 17/3/6.
//  Copyright © 2017年 cqjr. All rights reserved.
//

#import "YZMPhoneNewViewController.h"
#import "YZMAuthCodeView.h"
#import "YZGeneralResultModel.h"
#import "YZClient.h"
#import "YZMAppHelper.h"
#import <BlocksKit/UIControl+BlocksKit.h>
#import "YZMAlertView.h"

@interface YZMPhoneNewViewController ()<UITextFieldDelegate>

@property (nonatomic, strong) YZMAuthCodeView *authCodeView;
@property (nonatomic, copy) NSString *sourcePageName;

@end

@implementation YZMPhoneNewViewController{
    UIButton *_nextStepButton;
}

- (id)init {
    
    if (self = [super init]) {
        self.navigationItem.title = @"手机绑定";
        self.hidesBottomBarWhenPushed = YES;
        self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    }
    
    return self;
}

- (void)dealloc {
    
    [self removeTimer];
}

- (void)removeTimer {
    
    if (self.authCodeView.timer && [self.authCodeView.timer isValid]) {
        
        [self.authCodeView.timer invalidate];
    }
    self.authCodeView.timer = nil;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self createObjects];
}

- (void)createObjects  {
    
    self.authCodeView = [[YZMAuthCodeView alloc] initWithScene:SEND_CODE_SCENE_FOR_BIND_NEWMOBILE];
    [self.view addSubview:self.authCodeView];
    [self.authCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(108);
    }];
    [self.authCodeView.textField addTarget:self action:@selector(textFieldchange:) forControlEvents:UIControlEventEditingChanged];
    self.authCodeView.textField.delegate = self;
    [self.authCodeView.phoneTextField addTarget:self action:@selector(textFieldchange:) forControlEvents:UIControlEventEditingChanged];
    self.authCodeView.phoneTextField.delegate = self;
    
    _nextStepButton = [YZMAppStyle NewsubmitButton];
    _nextStepButton.enabled = NO;
    [_nextStepButton setTitle:@"绑定" forState:UIControlStateNormal];
    [_nextStepButton addTarget:self action:@selector(nextStepCheck:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextStepButton];
    
    [_nextStepButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(self.view).with.offset(ControlSpacing20);
        make.right.equalTo(self.view).with.offset(-ControlSpacing20);
        make.top.equalTo(self.authCodeView.mas_bottom).with.offset(ControlSpacing20);
    }];
    
    
    UILabel *textLabel = [YZMAppStyle labelWithMediumWhite];
    textLabel.textColor = [YZMAppStyle colorForLightGrayText];
    [self.view addSubview:textLabel];
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nextStepButton.mas_bottom).offset(14);
        make.centerX.equalTo(self.view);
    }];
    textLabel.userInteractionEnabled = YES;
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:@"如有问题，请联系客服"];
    [string addAttribute:NSForegroundColorAttributeName value:[UIColor clearColor] range:NSMakeRange(6, 4)];
    textLabel.attributedText = string;
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [textLabel addSubview:button];
    [button setTitleColor:[YZMAppStyle colorForLightBlueText] forState:UIControlStateNormal];
    button.titleLabel.font = [YZMAppStyle mediumSizeFont];
    [button setTitle:@"联系客服" forState:UIControlStateNormal];
    [button bk_addEventHandler:^(id sender) {
        
        [YZMAppHelper callServicePhone];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    [button mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(textLabel);
        make.right.equalTo(textLabel);
    }];
}

- (BOOL)textFieldCheck {
    
    if ([self.authCodeView.phoneTextField.text yz_isValidPhoneString]) {
        
        if (![self phoneCheck]) {
            
            [MBProgressHUD showMessage:@"请输入正确的手机号码"];
            return NO;
        }
    } else {
        
        [MBProgressHUD showMessage:@"请输入正确的手机号码"];
        return NO;
    }
    
    if (!self.authCodeView.getAuthFlag) {
        
        [MBProgressHUD showMessage:@"请先获取验证码"];
        return NO;
    }
    
    if (![self.authCodeView.textField.text yz_isWithdrawPwdCode]) {
        
        [MBProgressHUD showMessage:@"请输入6位数字验证码"];
        return NO;
    }
    
    return YES;
}

- (BOOL)phoneCheck {
    
    NSInteger phoneNum = [[self.authCodeView.phoneTextField.text substringToIndex:2] integerValue];
    switch (phoneNum) {
        case 13:
        case 14:
        case 15:
        case 17:
        case 18:
            return YES;
            break;
        default:
            return NO;
            break;
    }
}

- (void)textFieldchange:(UITextField *)send {
    
    if ([self.authCodeView.phoneTextField.text length] > 0 &&
        [self.authCodeView.textField.text length] > 0) {
        
        _nextStepButton.enabled = YES;
        return;
    }
    
    _nextStepButton.enabled = NO;
}

-(void)resignFirstResponderAll{
    
    [self.view endEditing:YES];
}

- (void)nextStepCheck:(UIButton *)send {
    
    [self resignFirstResponderAll];
    
    if (![self textFieldCheck]) {
        
        return;
    }
    
    NSString *phoneStr = self.authCodeView.phoneTextField.text;
    NSString *checkCode = self.authCodeView.textField.text;
    
    
    [YZClient bind_NewMobileWithMobile:phoneStr withCheckCode:checkCode success:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            [YZMCMInstance popViewControllerToControllerName:self.sourcePageName animated:YES];
        }else{
            YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:topModel.resultMessage];
            [alertView show];
//            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self resignFirstResponderAll];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - manager

+ (instancetype)createWithParams: (NSDictionary *)params{
    YZMPhoneNewViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

- (void)updateWithParams: (NSDictionary *)params{
    
    self.sourcePageName = params[YZSOURCEPAGE];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
